#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/13 13:58
# File  : pass_crypt.py

"""
加密密码工具类
"""
from cryptography.fernet import Fernet


class PasswordCrypt(object):
    """
    加密密码后存储，对称加密，可以通过key反解，key因为要解密这里写死，生成方式如下
    key = base64.urlsafe_b64encode(os.urandom(32))
    """
    def __init__(self):
        self.key = 'JS4ghxEHEG21Uz9_iegO8p1oTp-Ij6surOV34zQYTKc='

    def encrypt(self, password):
        """加密，传入明文，返回加密后的密文字符"""
        f = Fernet(self.key)
        password_encode = password.encode()
        token = f.encrypt(password_encode)
        return token.decode()

    def decrypt(self, token):
        """解密，传入密文，返回解密后的明文密码"""
        f = Fernet(self.key)
        token_encode = token.encode()
        password = f.decrypt(token_encode)
        return password.decode()
